package com.zhangwei.xmppdemo.xmpp;

import android.os.AsyncTask;
import android.util.Log;

import com.zhangwei.xmppdemo.xmpp.api.XmppCallBack;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.iqregister.AccountManager;

import java.io.IOException;

/**
 * @version V1.0
 * @description:
 * @title: Expands
 * @package com.zhangwei.expands.xmpp
 * @author: zhangwei
 * @date: 2015-12-18 上午10:19
 * Xmpp工具类
 * 第一步  必须链接服务器
 */
public class XmppHelper {
    //    Xmpp及时通信核心类
    private static XMPPTCPConnection connection;
    private static XmppHelper helper;
    private static final String SERVER_HOST = "10.6.155.52";
    private static final int SERVER_PORT = 5222;
    private static final String SERVER_NAME = "www.qianfeng.com";

    private XmppHelper() {
    }

    synchronized public static XmppHelper getInstance() {
        if (helper == null) {
            helper = new XmppHelper();
        }
        return helper;
    }

    /**
     * 初始化即时通信
     */
    public void init() {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                openXMPPTCPConnection();
                return null;
            }
        }.execute();
    }

    /**
     * 连接服务器
     */
    public XMPPTCPConnection openXMPPTCPConnection() {
        if (connection == null || connection.isSmAvailable()) {
            XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
            //设置服务器ip地址
            builder.setHost(SERVER_HOST);
            //设置服务器端口号  默认 5222
            builder.setPort(SERVER_PORT);
            //设置服务器的名称
            builder.setServiceName(SERVER_NAME);
            //开启dug模式 打印错误日志  正式版注意关闭
            builder.setDebuggerEnabled(true);
            //设置是否启用压缩
            builder.setCompressionEnabled(true);
            //设置是否启用TLS安全协议
            builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
//            builder.setUsernameAndPassword("wh1502", "123456");
//            CA
//            builder.setKeystoreType()
            connection = new XMPPTCPConnection(builder.build());
//            connection.addConnectionListener(ConnectionListener);
            try {
                connection.connect();


            } catch (SmackException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (XMPPException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    /**
     * 登陆
     *
     * @param name
     * @param password state =-1  登陆失败,1表示成功  2表示表示连接服务器失败
     */
    public void login(final String name, final String password, final XmppCallBack<Integer> callBack) {

        new AsyncTask<Void, Void, Integer>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                if (callBack != null) {
                    callBack.onStart();
                }
            }

            @Override
            protected Integer doInBackground(Void... params) {
                int state = -1;
                try {
                    openXMPPTCPConnection().login(name, password);
                    chat();
                    state = 1;
                } catch (Exception e) {
                    e.printStackTrace();
                    state = 2;
                }
                return state;
            }

            @Override
            protected void onPostExecute(Integer integer) {
                super.onPostExecute(integer);
                if (callBack != null) {
                    callBack.onSuccess(integer);
                }
            }
        }.execute();
    }

    /**
     * <li>name -- the user's name.
     * <li>first -- the user's first name.
     * <li>last -- the user's last name.
     * <li>email -- the user's email address.
     * <li>city -- the user's city.
     * <li>state -- the user's state.
     * <li>zip -- the user's ZIP code.
     * <li>phone -- the user's phone number.
     * <li>url -- the user's website.
     * <li>date -- the date the registration took place.
     * <li>misc -- other miscellaneous information to associate with the account.
     * <li>text -- textual information to associate with the account.
     * <li>remove -- empty flag to remove account.
     *
     * @param name
     * @param password
     */
    public void resiter(String name, String password) {
        /**
         * 创建用户管理类
         */
        AccountManager manager = AccountManager.getInstance(openXMPPTCPConnection());
        try {


            manager.createAccount(name, password);
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }

    }

    /**
     * 注册一个用户
     */
    public void chat() {

        ChatManager chatManager = ChatManager.getInstanceFor(openXMPPTCPConnection());
        chatManager.addChatListener(new ChatManagerListener() {
            @Override
            public void chatCreated(Chat chat, boolean createdLocally) {
                chat.addMessageListener(new ChatMessageListener() {
                    @Override
                    public void processMessage(Chat chat, Message message) {
                        Log.e("body", message.getBody());
                    }
                });
            }
        });
    }


}
